import CoderViewer from '@/components/CodeViewer'
import { useEffect, useState } from 'react'
import axios from 'axios'
import compute, { process_before_compute, list2str } from '@/utils/dpbt'

const oursColor = '#0000ff'
const theirsColor = '#ff0000'
const opacity = 0.2

export default function Home() {
    const [versions, setVersions] = useState([])
    const [idx, setIdx] = useState(null)
    const [OBdiffs, setOBDiffs] = useState([])
    const [TBdiffs, setTBdiffs] = useState([])
    // const [generated, setGenerated] = useState('')

    useEffect(() => {
        const getVersions = async () => {
            try {
                const res = await axios.get('/api/versions')
                setVersions(res.data)
                if (res.data.length > 0) {
                    setIdx(0)
                }
            } catch (e) {
                console.error(e)
            }
        }
        getVersions()
    }, [])

    useEffect(() => {
        if (idx === null) return
        setOBDiffs(compute(versions[idx].base, versions[idx].ours))
        setTBdiffs(compute(versions[idx].base, versions[idx].theirs))

        // 获取 combine resolver 给出的结果
        // const getOfferable = async () => {
        //     try {
        //         const res = await axios.post('http://localhost:3001/combine', {
        //             version1: versions.ours,
        //             version2: versions.theirs,
        //             base: versions.base,
        //         })
        //         setGenerated(res.data.data)
        //     } catch (e) {
        //         console.error(e)
        //     }
        // }
        // getOfferable()
    }, [idx, versions])

    useEffect(() => {
        console.log('OBdiffs:', OBdiffs)
        console.log('TBdiffs:', TBdiffs)

        const createdElements = []
        const generateBlock = (start, end, id, rgb, opacity) => {
            const hex2rgb = hex => {
                const r = parseInt(hex.slice(1, 3), 16)
                const g = parseInt(hex.slice(3, 5), 16)
                const b = parseInt(hex.slice(5, 7), 16)
                return [r, g, b]
            }
            const [r, g, b] = hex2rgb(rgb)
            const paintedBlock = document.createElement('div')
            paintedBlock.style.pointerEvents = 'none'
            createdElements.push(paintedBlock)
            paintedBlock.style.position = 'absolute'
            paintedBlock.style.left = '0px'
            paintedBlock.style.top = `${6.5 + start * 15}px`
            paintedBlock.style.width = '100%'
            paintedBlock.style.height = `${
                (end - start) * 15 > 0 ? (end - start) * 15 : 2
            }px`

            paintedBlock.style.backgroundColor = `rgba(${r}, ${g}, ${b}, ${opacity})`
            const parent = document.getElementById(id)
            parent.appendChild(paintedBlock)
            return paintedBlock
        }
        const generateConnection = (
            start1,
            end1,
            start2,
            end2,
            id1,
            rgb,
            opacity,
        ) => {
            const hex2rgb = hex => {
                const r = parseInt(hex.slice(1, 3), 16)
                const g = parseInt(hex.slice(3, 5), 16)
                const b = parseInt(hex.slice(5, 7), 16)
                return [r, g, b]
            }
            const [r, g, b] = hex2rgb(rgb)
            const parent = document.getElementById(id1)

            // 创建 <svg> 元素
            const svg = document.createElementNS(
                'http://www.w3.org/2000/svg',
                'svg',
            )
            svg.style.overflow = 'visible'
            svg.setAttribute('width', '200')
            svg.setAttribute('height', '100')
            svg.style.position = 'absolute'
            svg.style.zIndex = 999
            svg.style.left = '100%'
            svg.style.top = '0px'

            // 创建 <polygon> 元素
            const polygon = document.createElementNS(
                'http://www.w3.org/2000/svg',
                'polygon',
            )
            polygon.setAttribute(
                'points',
                `-${6.5 + start1 * 15},0 -${
                    end1 == start1 ? 8.5 + end1 * 15 : 6.5 + end1 * 15
                },0 -${6.5 + end2 * 15},40 -${6.5 + start2 * 15},40`,
            )
            polygon.setAttribute('fill', `rgba(${r}, ${g}, ${b}, ${opacity})`)

            // 将 <polygon> 元素添加到 <svg> 元素中
            svg.appendChild(polygon)
            svg.style.transformOrigin = 'top left'
            svg.style.transform = 'rotate(-90deg)'

            // 将 <svg> 元素添加到父元素中
            parent.appendChild(svg)
            createdElements.push(svg)
        }
        // 绘制差异块指示
        if (!OBdiffs || !TBdiffs) {
            console.error(
                'diffs not ready, OBdiffs:',
                OBdiffs,
                'TBdiffs:',
                TBdiffs,
            )
            return
        }
        for (const diff of OBdiffs) {
            generateBlock(
                diff.seq1Range.start,
                diff.seq1Range.end,
                'base',
                oursColor,
                opacity,
            )

            generateBlock(
                diff.seq2Range.start,
                diff.seq2Range.end,
                'ours',
                oursColor,
                opacity,
            )

            generateConnection(
                diff.seq2Range.start,
                diff.seq2Range.end,
                diff.seq1Range.start,
                diff.seq1Range.end,
                'ours',
                oursColor,
                opacity,
            )
        }
        for (const diff of TBdiffs) {
            generateBlock(
                diff.seq1Range.start,
                diff.seq1Range.end,
                'base',
                theirsColor,
                opacity,
            )

            generateBlock(
                diff.seq2Range.start,
                diff.seq2Range.end,
                'theirs',
                theirsColor,
                opacity,
            )

            generateConnection(
                diff.seq1Range.start,
                diff.seq1Range.end,
                diff.seq2Range.start,
                diff.seq2Range.end,
                'base',
                theirsColor,
                opacity,
            )
        }
        return () => {
            for (const element of createdElements) {
                element.remove()
            }
        }
    }, [OBdiffs, TBdiffs])

    return (
        <>
            <header
                style={{
                    display: 'grid',
                    justifyContent: 'center',
                    justifyItems: 'center',
                    gridTemplateColumns: '100px 100px 100px',
                }}
            >
                <button
                    onClick={() => {
                        setIdx((idx - 1 + versions.length) % versions.length)
                    }}
                >
                    上一个
                </button>
                {idx === null ? (
                    <div>暂无版本</div>
                ) : (
                    <div>
                        {idx + 1} / {versions.length}
                    </div>
                )}
                <button
                    onClick={() => {
                        setIdx((idx + 1) % versions.length)
                    }}
                >
                    下一个
                </button>
            </header>
            {versions.length === 0 ? (
                <div>暂无版本</div>
            ) : (
                <>
                    <div
                        style={{
                            display: 'flex',
                            flexDirection: 'row',
                            width: '100%',
                            justifyContent: 'space-between',
                        }}
                    >
                        {['ours', 'base', 'theirs'].map(id => (
                            <CoderViewer
                                key={id}
                                codeText={list2str(
                                    process_before_compute(versions[idx][id]),
                                )}
                                title={id}
                                id={id}
                                width={'33.333%'}
                            />
                        ))}
                    </div>
                    <CoderViewer
                        codeText={list2str(
                            process_before_compute(versions[idx].resolution),
                        )}
                        title={'实际解决方案'}
                        id={'resolve'}
                    />
                </>
            )}
            {/* <CoderViewer
                codeText={generated}
                title={'生成推荐方案'}
                id={'generated'}
            /> */}
        </>
    )
}
